"ui";
ui.layout(
    <scroll>
        <vertical padding="16">
            <text
                textSize="16sp"
                textColor="black"
                text="此控件不显示"
                visibility="gone"
            />
            <text textSize="16sp" textColor="black" text="Autojs UI demo" />
            <text textSize="16sp" textColor="black" text="By:Abner" />

            <text textSize="16sp" textColor="black" text="请输入用户编号" />
            <input id="username" text="" />

            <checkbox id="needCheck" text="校验" checked="true" />

            <button id="ok" text="确定" />

            <text marginTop="100px" text="日志" />
            <com.stardust.autojs.core.console.ConsoleView
                h="1500dp"
                id="console"
            />
        </vertical>
    </scroll>
);

ui.console.setConsole(runtime.console);
// 设置控制台字体颜色
let c = new android.util.SparseArray();
let Log = android.util.Log;
c.put(Log.VERBOSE, new java.lang.Integer(colors.parseColor("#dfc0c0c0")));
c.put(Log.DEBUG, new java.lang.Integer(colors.parseColor("#cc000000")));
c.put(Log.INFO, new java.lang.Integer(colors.parseColor("#ff64dd17")));
c.put(Log.WARN, new java.lang.Integer(colors.parseColor("#ff2962ff")));
c.put(Log.ERROR, new java.lang.Integer(colors.parseColor("#ffd50000")));
c.put(Log.ASSERT, new java.lang.Integer(colors.parseColor("#ffff534e")));
ui.console.setColors(c);

var needCheck = true;
var username = "";

//确保/sdcard/Android/文件夹存在
var path = "/sdcard/Android/2.jpg";
files.ensureDir(path);

var localStorage = storages.create("uidemo");
loadCache();

function saveCache() {
    var cacheData = {
        needCheck: ui.needCheck.isChecked(),
        username: ui.username.getText().toString().trim(),
    };
    log("save cache");
    log(cacheData);
    localStorage.put("cacheData", cacheData);
}
function loadCache() {
    var defaultCacheData = {
        needCheck: true,
        username: "",
    };
    var cacheData = localStorage.get("cacheData", defaultCacheData);
    log("load cache");
    log(cacheData);
    initData(cacheData);
}
function initData(cacheData) {
    needCheck = cacheData.needCheck;
    username = cacheData.username;

    ui.needCheck.checked = needCheck;
    ui.username.setText(username);
}

//指定确定按钮点击时要执行的动作
ui.ok.click(function () {
    threads.start(function () {
        do_start();
    });

    threads.start(function () {
        while (true) {
            //这边可以用来监控手机的一些非必要弹框，比如权限申请，应用崩溃等
            if (text("关闭应用").exists()) {
                clickUiBounds(text("关闭应用"));
            }
            if (text("关闭应用程序").exists()) {
                clickUiBounds(text("关闭应用程序"));
            }
            if (text("重新打开应用").exists()) {
                clickUiBounds(text("重新打开应用"));
            }
            clickUiBounds(text("以后再说"));
            clickUiBounds(text("允许"));
            sleep(2000);
        }
    });
});

function do_start() {
    (needCheck = ui.needCheck.isChecked()),
        (username = ui.username.getText().toString().trim()),
        saveCache();

    if (needCheck && username != "abner") {
        alert("你想干啥？！");
        return;
    }

    log("请确保开启无障碍服务哦~");
    // auto.waitFor()
    auto();

    home();
    console.show();
    log("开始");
    sleep(1000);
    requestScreenshot();

    try {
        cap();
    } catch (e) {
        console.error(e);
    }
}

function cap() {
    try {
        console.clear();
        sleep(200);

        captureScreen(path);
        sleep(555);
        var img = images.read(path);
        sleep(111);
        images.save(img, path, "jpg", 10);
        // var a = new Date().getTime();
        // images.save(img,  "/sdcard/Android/" + a + "_1.jpg", "jpg", 10);
        sleep(111);
        // console.show();
        log("截图完毕");

        if (!files.exists(path)) {
            console.error("截图失败,3秒后重试!");
            sleep(3000);
            return cap();
        }
    } catch (e) {
        console.error(e);
    }
    return "";
}

function consoleClick(ui) {
    if (!ui.exists()) {
        return;
    }
    console.hide();
    sleep(200);
    var result = clickUiBounds(ui);
    sleep(200);
    console.show();
    return result;
}
/**
 *  不能点击的控件，通过坐标点击
 * @param {*} uiSelector
 */
function clickUiBounds(ui) {
    try {
        if (ui.exists()) {
            var a = ui.findOnce();
            if (a) {
                if (a.clickable()) {
                    a.click();
                    return true;
                } else {
                    var b = a.bounds();
                    if (b) {
                        click(b.centerX(), b.centerY());
                        return true;
                    }
                }
            }
        }
    } catch (e) {
        console.error(e);
    }
    return false;
}

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function exitApp() {
    for (var i = 0; i < 5; i++) {
        back();
        sleep(200);
    }
}

function checkAppOpened(pname) {
    if (!packageName(pname).exists()) {
        app.launchPackage(pname);
        sleep(5000);
    }
}

function myWaitFor(ui, times) {
    times = times | 10;
    for (var i = 0; i < times; i++) {
        if (ui.exists()) {
            sleep(200);
            return true;
        }
        sleep(1000);
    }
    return false;
}

function myWaitForTwo(ui, ui2, times) {
    times = times | 10;
    for (var i = 0; i < times; i++) {
        if (ui.exists() || ui2.exists()) {
            sleep(200);
            return true;
        }
        sleep(1000);
    }
    return false;
}

function skipOpenAppAd(times) {
    imes = times | 10;
    for (var i = 0; i < times; i++) {
        if (clickUiBounds(text("跳过")) || clickUiBounds(desc("跳过"))) {
            break;
        }
        sleep(1000);
    }
}

function requestScreenshot() {
    let result = false;
    let thread = threads.start(function () {
        let i = 0;
        while (i < 5) {
            clickNode("text", "立即开始");
            clickNode("text", "START NOW");
            i++;
            sleep(1111);
        }
    });
    if (!requestScreenCapture()) {
        log("请求截图失败");
    } else {
        result = true;
        thread.interrupt();
    }
    return result;
}

function clickNode(way, content, milliSecond) {
    if (!milliSecond) {
        milliSecond = 1000;
    }
    let result = false;
    if (!content) {
        return result;
    }
    let object;
    if (way == "text") {
        object = text(content).visibleToUser(true).findOne(milliSecond);
    } else if (way == "desc") {
        object = desc(content).visibleToUser(true).findOne(milliSecond);
    } else if (way == "id") {
        object = id(content).visibleToUser(true).findOne(milliSecond);
    } else if (way == "className") {
        object = className(content).visibleToUser(true).findOne(milliSecond);
    }
    if (object != null) {
        if (object.clickable()) {
            result = object.click();
            result && sleep(1111);
        }
    }
    return result;
}

function closeApp(packageName) {
    console.log("关闭进程?->?" + packageName);
    var result = shell("am force-stop " + packageName, true);
    log(result);
}

function resetApp(packageName) {
    console.log("清理缓存?->?" + packageName);
    var result = shell("pm clear " + packageName, true);
    log(result);
}

function installApp(path) {
    shell("pm install -r " + path, true);
}
function uninstallApp(packageName) {
    var version = getPackageVersionName(packageName);
    if (!version) {
        log("app" + packageName + "不存在，无需卸载!");
        return;
    }
    console.log("卸载应用?->?" + packageName);
    var result = shell("pm uninstall " + packageName, true);
    log(result);
}

function 下载文件(url, savePath) {
    try {
        var r = http.get(url);
        log("code=", r.statusCode);
        var zipFile = r.body.bytes();
        if (zipFile) {
            files.writeBytes(savePath, zipFile);
        } else {
            console.error("下载文件失败");
            // exit()
        }
    } catch (err) {
        console.error(err);
        // exit()
        console.error("下载文件失败,3秒后重试");
        sleep(3000);
        下载文件(url, savePath);
    }
}

/**
 * 坐标找色 (云机不好用？)
 * color 为 #67DCA0
 */
function detectsColor(color, x, y) {
    var a = new Date().getTime();
    var path = "/sdcard/Android/" + a + "_1.jpg";
    var isCapFinish = false;
    threads.start(function () {
        toastLog("开始截屏");
        shell("screencap -p " + path, true);
        toastLog("截屏结束");
        isCapFinish = true;
    });
    while (true) {
        if (isCapFinish) {
            break;
        }
        toastLog("等待截屏结束");
        sleep(1000);
    }
    var img = images.read(path);
    if (images.detectsColor(img, color, x, y)) {
        return true;
    } else {
        return false;
    }
}
function clickScale(x, y, sourceWidth, SourceHeight) {
    x = (x * device.width) / sourceWidth;
    y = (y * device.height) / SourceHeight;
    click(x, y);
}
/**
 * 区域找色
 * @param {*} -9970528
 * @param {*} x
 * @param {*} y
 */
function pixelDiff(color, x, y) {
    var a = new Date().getTime();
    var path = "/sdcard/Android/" + a + "_1.jpg";
    var isCapFinish = false;
    threads.start(function () {
        toastLog("开始截屏");
        shell("screencap -p " + path, true);
        toastLog("截屏结束");
        isCapFinish = true;
    });
    while (true) {
        if (isCapFinish) {
            break;
        }
        toastLog("等待截屏结束");
        sleep(1000);
    }
    var img = images.read(path);
    var result = images.pixel(img, x, y);
    log(result);
    log(color - result);
    if (Math.abs(color - result) < 2000000) {
        return true;
    } else {
        return false;
    }
    // if(images.detectsColor(img, color, x, y)){
    //     return true;
    // }else{
    //     return false;
    // }
}
